package com.example.kotlinstudy.fragment

import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.kotlinstudy.R


/**
 * A simple [Fragment] subclass.
 * Use the [ListFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class ListFragment : Fragment() {

    // 定义一个接口，用于监听列表项的选择事件(约束行为)
    interface OnItemSelectedListener {
        // 当列表项被选中时调用此方法，并传递选中的项ID
        fun onItemSelected(itemId: Int)
    }

    // 声明一个变量来保存实现了OnItemSelectedListener接口的监听器实例
    private var listener: OnItemSelectedListener? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 分别给 按钮1,item1 按钮2,item2 绑定点击事件，点了之后 通过 listener 调用  onItemSelected ，分别传递 索引
        view.findViewById<View>(R.id.item1).setOnClickListener {
            listener?.onItemSelected(0)
            // 跳转到详情页

        }
        view.findViewById<View>(R.id.item2).setOnClickListener {
            listener?.onItemSelected(1)
        }

    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        Log.d("ListFragMent", "onAttach")
        if (context is OnItemSelectedListener) {
            // 如果实现了，则将listener设置为该Activity的实例
            listener = context
        } else {
            // 如果没有实现，则抛出运行时异常提示必须实现OnItemSelectedListener接口
            throw RuntimeException("$context 必须实现 OnItemSelectedListener")
        }
    }

    override fun onDetach() {
        super.onDetach()
        Log.d("ListFragMent", "onDetach")
        listener = null
    }


}